<?php /* УТФ-8:fix */

class SPIstore__pgsql__query
{
    private $db_handler;
    private $query_handler;
    private $fetch_index;
    private $manual_limit;
    private $num_rows;

    private $is_failed;
    private $last_error_message;

    public function __construct( $db_handler, $query, $params = null )
    {
        $this->db_handler    = $db_handler;

        if( is_array( $params ) === true && count( $params ) > 0 )
        {
            $this->query_handler = pg_query_params( $this->db_handler, $query, $params );
        }
        else
        {
            $this->query_handler = pg_query( $this->db_handler, $query );
        }

        if( is_resource( $this->query_handler ) === true )
        {
            $this->is_failed            = false;

            $this->num_rows             = pg_num_rows( $this->query_handler );
            $this->fetch_index          = 0;
            $this->manual_limit         = null;
            $this->last_error_message   = null;
        }
        else
        {
            $this->is_failed            = true;
            $this->last_error_message   = pg_last_error( $this->db_handler );
        }
    }

    public function fetch( $fetch_field = null )
    {
        if( is_resource( $this->query_handler ) === false )
        {
            return false;
        }

        if( $this->manual_limit !== null )
        {
            if( $this->manual_limit == 0 )
            {
                return false;
            }

            $this->manual_limit--;
        }

        if( $this->fetch_index >= $this->num_rows )
        {
            return false;
        }

        if( $fetch_field === null )
        {
            return pg_fetch_array( $this->query_handler, $this->fetch_index++, PGSQL_ASSOC );
        }

        $item = pg_fetch_array( $this->query_handler, $this->fetch_index++, PGSQL_ASSOC );

        return $item[ $fetch_field ];
    }

    public function fetch_and_close( $fetch_field = null )
    {
        $result = $this->fetch( $fetch_field );
        $this->close();

        return $result;
    }

    public function seek( $offset )
    {
        $this->fetch_index = $offset;
        return true;
    }

    public function set_manual_limit( $limit )
    {
        $this->manual_limit = $limit;
        return true;
    }

    public function num_rows()
    {
        return $this->num_rows;
    }

    public function close()
    {
        if( is_resource( $this->query_handler ) === true )
        {
            pg_free_result( $this->query_handler );
            return true;
        }
        return false;
    }

    public function is_failed()
    {
        return $this->is_failed;
    }

    public function get_last_error_message()
    {
        return $this->last_error_message;
    }
}
